<template>
  <div>
    <el-form ref="userForm" size="small" :model="entity" :rules="rules" label-width="120px" @submit.native.prevent>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="entity.username" placeholder="用户名" ref="username" />
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input v-model="entity.pwd" show-password placeholder="密码" />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="entity.name" placeholder="姓名" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="entity.phone" placeholder="手机号" />
      </el-form-item>
      <el-form-item label="企业微信" prop="wxuid">
        <el-input v-model="entity.wxuid" placeholder="企业微信" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="btnSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  props:{
    entityId : {type : Number, default: 0}
  },
  data() {
    return {
      entity: {
        username: '',
        pwd : '',
        name: '',
        phone:'',
        wxuid:'',
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {
    this.loadEntity();
    this.$nextTick(()=>{
      this.$refs.username.focus()
    })
  },
  methods: {
    loadEntity(){
      if(this.entityId > 0){
        request({ url: '/sys/useradmin/getuser', data: {id : this.entityId} }).then( res =>{
          this.entity = res.data
        })
      }
    },
    btnSubmit(){
      this.$refs['userForm'].validate((valid) => {
        if(valid){
          request({
            url: '/sys/useradmin/addedituser',
            data: this.entity
          }).then( res =>{
            if(res.code === "200"){
              this.$message.success(res.msg)
              this.$emit('update:visible', false);  //关闭弹窗
              //触发事件总线，让列表界面更新数据
              this.entityId > 0 ? this.$EventBus.$emit("useredit", {}):this.$EventBus.$emit("useradd", {})
            }else{
              this.$message.error(res.msg);
            }
          })
        }else{
          console.log('error submit!!');
          return false;
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
